
<template>
    <PageTabelLayout>
        <template #pageHeader>
            <div class="my-header">
                <div class="my-tool-bar">
                    <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="delHandler" @select="selectHandler" />
                </div>
            </div>
        </template>
        <template #pageTabel>
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple"
                @grid-ready="gridReady" style="height:100%" class='ag-theme-alpine' :defaultColDef="defaultColDef"
                :rowData="table.dataList" :columnDefs="cfsValue" :localeText="localeTextData" />
        </template>
        <paginationCopys :total="total" show-total show-jumper show-page-size @change="changePage"
            @page-size-change="changeSize" style="justify-content: center" :page-size="pagination.pageSize"
            :current="pagination.page" />
        <a-drawer :drawer-style="{ zIndex: 9999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd"
            unmountOnClose @ok="sideOk" @cancel="pageData.showAdd = false" cancel-text="关闭" ok-text="保存"
            :ok-loading="loadings">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" auto-label-width :model="dataForm">
                    <a-form-item label="测试方法" field="verifyMethod" :validate-trigger="['change', 'blur']"
                        :rules="[{ required: true, message: '测试方法必填' }]" label-col-flex="80px">
                        <a-input @blur="dataForm.verifyMethod = dataForm.verifyMethod?.toUpperCase()"
                            v-model="dataForm.verifyMethod" class="bacClass" />
                    </a-form-item>
                    <a-form-item label="备注" field="remark" label-col-flex="80px">
                        <a-input v-model="dataForm.remark" class="bacClass" />
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
    </PageTabelLayout>
</template>

<script lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import vaildate from '@/hooks/useValidate'
import { TestMethod } from '@/interface/physicalBasicData'
import { FormInstance, Message, Modal } from '@arco-design/web-vue'
import { testMethod } from '@/api/PhysicalSurveyRoom/basicDataApi';
import PageTabelLayout from '@/components/pageTabelLayout.vue'

import { localeText } from '@/api/aggridZw'
import emitter from "@/hooks/useEventBus";
export default {
    name: "testMethod",
    setup() {
        onMounted(() => {
            // 第一个页面需要在刚进入就调用一次  切换tap时也需要调用
            doRefresh();
            emitter.on("refresh-testMethod", () => {
                doRefresh();
                gridOption.value.sizeColumnsToFit();
            });
        });
        const testMethodApi = testMethod();
        const selectHandler = () => {
            pagination.page = 1;
            doRefresh();
        };
        const addHandler = () => {
            for (var key in dataForm) {
                if (key === "id") {
                    dataForm[key] = null;
                }
                else if (key == "serialNo") {
                    dataForm[key] = 0;
                }
                else {
                    dataForm[key] = "";
                }
            }
            pageData.showAdd = true;
            pageData.sideTitle = "新增测试方法";
        };
        const delHandler = () => {
            let vals = gridOption.value.getSelectedRows().map((v: any) => { return v.id });
            if (vals.length > 0) {
                Modal.confirm({
                    title: "提示",
                    content: "确定要批量删除选中数据吗？",
                    cancelText: "取消",
                    okText: "删除",
                    onOk: async () => {
                        await testMethodApi.batchDelTestMethod([...vals]).then((res) => {
                            if (res.code === 200) {
                                Message.success("数据删除成功");
                                pagination.page = 1;
                                doRefresh();
                            } else {
                                Message.success("数据删除失败");
                            }
                        });
                    },
                });
            }
            else {
                Message.info("请选择需要删除的数据");
            }
        };
        const editHandler = (record: TestMethod) => {
            pageData.showAdd = true;
            pageData.sideTitle = "编辑测试方法";
            for (var key in record) {
                dataForm[key] = record[key];
            }
        };
        async function doRefresh() {
            pageData.pageLoading = true;
            await testMethodApi.getPageTestMethodList({
                page: pagination.page,
                size: pagination.pageSize,
                deleteState: 0,
            }).then(({ code, data }) => {
                if (code === 200) {
                    gridOption.value.sizeColumnsToFit();
                    table.handleSuccess(data.list);
                    gridOption.value.setRowData(data.list);
                    total.value = data.total;
                }
            }).catch(console.log).finally(() => {
                pageData.pageLoading = false;
            });
        }
        const formRef = ref<FormInstance>();
        const sideOk = () => {
            formRef.value?.validate().then(async (err) => {
                if (!err) {
                    loadings.value = true
                    if (dataForm.id) {
                        await testMethodApi.editTestMethod([{ ...dataForm }]).then((res) => {
                            if (res.code == 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;
                                Message.success({
                                    content: "修改成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            } else {
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                        }).catch((res) => {
                            console.log(res);
                        }).finally(() => {
                            loadings.value = false
                        })
                    } else {
                        await testMethodApi.addTestMethod([{ ...dataForm }]).then((res) => {
                            if (res.code == 200) {
                                formRef.value?.resetFields();
                                pageData.showAdd = false;
                                Message.success({
                                    content: "新增成功",
                                    duration: 5000,
                                });
                                doRefresh();
                            }else{
                                Message.error({
                                    content: res.message,
                                    duration: 5000,
                                });
                            }
                        }).catch((res) => {
                            console.log(res);
                        }).finally(() => {
                            loadings.value = false
                        })
                    }
                }
                else {
                    console.log(err);
                }
            });
        };
        const scrollbar = ref(true);
        const pagination = usePagination(doRefresh);
        const { selectedRowKeys } = useRowSelection();
        const table = useTable();
        const rowKey = useRowKey("id");
        const pageData = reactive<{
            showAdd: boolean;
            sideTitle: string;
            pageLoading: boolean;
        }>({
            showAdd: false,
            sideTitle: "新增测试方法",
            pageLoading: false,
        });
        const dataForm = reactive<TestMethod>({
            id: null,
            serialNo: 0,
            verifyMethod: "",
            remark: "",
            createTime: "",
            createName: "",
            updateName: "",
            updateTime: "",
        });
        //检验表单是否含有中文的方法
        const hasChiese = vaildate.includeChinese;
        const tableColumns = useTableColumn([
            {
                title: "序号",
                key: "serialNo",
                dataIndex: "serialNo",
                width: 150,
            },
            {
                title: "测试方法",
                key: "verifyMethod",
                dataIndex: "verifyMethod",
                width: 150,
            },
            {
                title: "备注",
                key: "remark",
                dataIndex: "remark",
                width: 150,
            },
            {
                title: "建立人",
                key: "createName",
                dataIndex: "createName",
                width: 150,
            },
            {
                title: "建立时间",
                key: "createTime",
                dataIndex: "createTime",
                width: 150,
            },
            {
                title: "修改人",
                key: "updateName",
                dataIndex: "updateName",
                width: 150,
            },
            {
                title: "修改时间",
                key: "updateTime",
                dataIndex: "updateTime",
                width: 150,
            },
            {
                title: "操作",
                key: "id",
                dataIndex: "id",
                slotName: "action",
                width: 150,
                fixed: "right",
            },
        ]);

        //表格方面
        const gridOption = ref();
        const gridReady = (params: any) => {
            gridOption.value = params.api;
            //调整表格自适应大小
            gridOption.value.sizeColumnsToFit();
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            flex: 1
        }
        let cfsValue: any[] = tableColumns.map(o => {
            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            if (o.slotName === 'action') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"
                obj["width"] = 120
                obj['cellRenderer'] = {
                    template: `<a-tag color="#ff7d00" @click="a" class="gesture">修改</a-tag>`,
                    setup(props: any) {
                        const a = () => {
                            editHandler(props.params.data)
                        }
                        return {
                            a
                        }
                    }

                }
            }

            return obj
        });
        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        cfsValue = a.concat(cfsValue);
        const total = ref(10);
        const changePage = (val: any) => {
            pagination.page = val
            doRefresh();
        }
        const changeSize = (val: any) => {
            pagination.pageSize = val
            doRefresh();
        }

        const localeTextData: any = ref(localeText);

        const loadings = ref(false)

        return {
            loadings,
            addHandler,
            delHandler,
            selectHandler,
            scrollbar,
            dataForm,
            editHandler,
            table,
            pagination,
            rowKey,
            hasChiese,
            tableColumns,
            selectedRowKeys,
            pageData,
            sideOk,
            formRef,
            changePage,
            changeSize,
            localeTextData,
            defaultColDef,
            gridReady,
            cfsValue,
            total
        };
    },
    components: { PageTabelLayout,  }
}
</script>

 
<style scoped>
.my-header {
    padding: 10px;
}

.aInput {
    width: 270px;
    background: #fff;
    border: 1px solid #c9cdd3;
}
</style>